﻿using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;

namespace HubClientHandler
{
    public class HubClient
    {               
        private string hubUri;
        private string hubName;

        private HubConnection hubConn;
        private IHubProxy hubProxy;

        public HubClient(string hubUri, string hubName) 
        {
            this.hubUri = hubUri;
            this.hubName = hubName;
        }

        public IHubProxy HubProxy 
        {
            get 
            {
                if (hubConn != null && hubConn.State != ConnectionState.Connected && hubProxy != null)
                    return hubProxy;

                if (StartHubClientIfRequired().Result)
                    return hubProxy;

                return null;
            }
        }
        
        private async Task<bool> StartHubClientIfRequired()
        {
            bool br = true;
            if (hubConn != null && hubConn.State != ConnectionState.Connected)
            {
                try
                {
                    hubConn.Stop();
                }
                catch 
                {
                }
                finally 
                { 
                    hubConn.Dispose();
                    hubConn = null;
                }
            }

            if (hubConn == null)
            {
                hubConn = new HubConnection(hubUri);
                hubProxy = hubConn.CreateHubProxy(hubName);
                try
                {
                    await hubConn.Start();
                }
                catch 
                {
                    br = false;
                }
            }

            return br;
        }
    }
}

